<template>
  <el-drawer
    v-model="drawerShow"
    title="设备管理"
    :close-on-click-modal="false"
    :before-close="sbBeforeClose"
    size="70%"
  >
    <div class="main h-[calc(100%-29px)]">
      <div class="w-full">
        <div v-if="queryShow" class="mb-[10px] w-full search-form">
          <el-form :inline="true" :model="queryForm.data" label-width="0px">
            <el-form-item>
              <el-input
                v-model="queryForm.data.blurry"
                clearable
                placeholder="输入设备名称搜索"
              />
            </el-form-item>
            <el-form-item class="ml-[10px]">
              <el-button type="primary" :icon="Search" @click="search"
                >搜索</el-button
              >
              <el-button :icon="RefreshLeft" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="w-full">
          <div class="w-full flex justify-between">
            <div class="buttons flex align-center">
              <el-button
                v-if="handleStatus !== 'look'"
                type="primary"
                :icon="Plus"
                @click="addMenu"
                >新增</el-button
              >
              <el-button
                v-if="handleStatus !== 'look'"
                type="success"
                :icon="Edit"
                :disabled="!(multipleSelection.length === 1)"
                @click="editSelect"
                >修改</el-button
              >
              <el-button
                v-if="handleStatus !== 'look'"
                type="danger"
                :icon="Delete"
                :disabled="!multipleSelection.length"
                @click="delSelect"
                >删除</el-button
              >
              <!--              <el-button type="warning" :icon="Download" @click="exportData"-->
              <!--                >导出</el-button-->
              <!--              >-->
            </div>
            <div class="settings">
              <el-button-group class="ml-4">
                <el-button
                  type="primary"
                  :icon="Search"
                  @click="queryShow = !queryShow"
                />
                <el-button
                  type="primary"
                  :icon="RefreshLeft"
                  @click="getList"
                />
                <el-popover placement="bottom" :width="200" trigger="click">
                  <template #reference>
                    <el-button type="primary" :icon="Grid" />
                  </template>
                  <el-checkbox
                    v-model="checkAll"
                    :indeterminate="isIndeterminate"
                    @change="handleCheckAllChange"
                    >全选</el-checkbox
                  >
                  <div class="group-box w-full max-h-[240px] overflow-y-auto">
                    <el-checkbox-group
                      v-model="checkedCities"
                      class="columns-show-group"
                      @change="handleCheckedCitiesChange"
                    >
                      <el-checkbox
                        v-for="item in defaultColums.data"
                        :key="item.prop"
                        :label="item.prop"
                        >{{ item.label }}</el-checkbox
                      >
                    </el-checkbox-group>
                  </div>
                </el-popover>
              </el-button-group>
            </div>
          </div>
          <div class="flex">
            <div class="role w-full">
              <div v-loading="loading" class="w-full mt-[10px]">
                <el-table
                  ref="multipleTableRef"
                  :data="tableData.data"
                  style="width: 100%"
                  row-key="id"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column type="selection" width="55" />

                  <el-table-column
                    v-for="item in colums.data"
                    :key="item.prop"
                    :prop="item.prop"
                    :label="item.label"
                    :width="item.width"
                    show-overflow-tooltip
                  >
                    <template
                      v-if="
                        ['status', 'equipType', 'equipStatus'].indexOf(
                          item.prop
                        ) > -1
                      "
                      #default="scope"
                    >
                      <span>{{
                        dictFormat(
                          item.prop,
                          scope.row[item.prop],
                          dictList.data[item.prop]
                        )
                      }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="操作" width="220">
                    <template #default="scope">
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        content="查看"
                        placement="top"
                      >
                        <el-button
                          type="primary"
                          size="small"
                          :icon="Document"
                          @click="lookRow(scope.row)"
                        />
                      </el-tooltip>
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        content="修改"
                        placement="top"
                      >
                        <el-button
                          v-if="handleStatus !== 'look'"
                          type="primary"
                          size="small"
                          :icon="Edit"
                          @click="editRow(scope.row)"
                        />
                      </el-tooltip>
                      <el-popconfirm
                        v-if="handleStatus !== 'look'"
                        width="200px"
                        title="确定删除本条数据吗？"
                        @confirm="delConfirm(scope.row)"
                      >
                        <template #reference>
                          <el-button
                            type="danger"
                            size="small"
                            :icon="Delete"
                          />
                        </template>
                      </el-popconfirm>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="page w-full mt-[10px]">
                <el-pagination
                  v-model:current-page="pageObj.data.currentPage"
                  v-model:page-size="pageObj.data.pageSize"
                  :page-sizes="[10, 20, 30, 40, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="pageObj.data.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-drawer
        v-model="addDialog"
        :title="title"
        :close-on-click-modal="false"
        :before-close="beforeClose"
        size="80%"
      >
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancel">取消</el-button>
            <el-button
              v-if="handleStatus !== 'look' && status !== 'look'"
              type="primary"
              @click="submit"
            >
              确认
            </el-button>
          </span>
        </template>
        <el-form
          ref="ruleForm"
          label-width="180px"
          :model="form.data"
          :rules="form.rules"
          :disabled="handleStatus === 'look' || status === 'look'"
        >
          <TitleGroup :title="'基础数据'">
            <el-row class="mt-[20px]">
              <el-col :span="12">
                <el-form-item label="设备名称" prop="name">
                  <el-input v-model="form.data.name" placeholder="设备名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备序号">
                  <el-input-number
                    v-model="form.data.equipSeqNo"
                    style="width: 100%"
                    placeholder="设备序号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备厂家">
                  <el-input
                    v-model="form.data.equipMaker"
                    placeholder="设备厂家"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备类型">
                  <el-select v-model="form.data.equipType" placeholder="请选择">
                    <el-option
                      v-for="item in dictList.data.equipType"
                      :key="item.id"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备描述">
                  <el-input
                    v-model="form.data.equipDescr"
                    placeholder="设备描述"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="资源状态">
                  <el-select v-model="form.data.status" placeholder="请选择">
                    <el-option
                      v-for="item in dictList.data.status"
                      :key="item.id"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人">
                  <el-input
                    v-model="form.data.contactName"
                    placeholder="联系人"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话">
                  <el-input
                    v-model="form.data.contactTel"
                    placeholder="联系电话"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </TitleGroup>
          <TitleGroup :title="'设备数据'">
            <el-row class="mt-[20px]">
              <el-col :span="12">
                <!--                <el-form-item label="上报设备状态">-->
                <!--                  <el-input-number-->
                <!--                    v-model="form.data.equipStatus"-->
                <!--                    style="width: 100%"-->
                <!--                    placeholder="上报设备状态"-->
                <!--                  />-->
                <!--                </el-form-item>-->
                <el-form-item label="上报设备状态">
                  <el-select
                    v-model="form.data.equipStatus"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in dictList.data.equipStatus"
                      :key="item.id"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="首次上线时间">
                  <el-date-picker
                    v-model="form.data.initOnlineTime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    type="datetime"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="上线时间">
                  <el-date-picker
                    v-model="form.data.onlineTime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    type="datetime"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="下线时间">
                  <el-date-picker
                    v-model="form.data.offlineTime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    type="datetime"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="有功遥测点号">
                  <el-input
                    v-model="form.data.pKey"
                    placeholder="有功遥测点号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="无功遥测点号">
                  <el-input
                    v-model="form.data.qKey"
                    placeholder="无功遥测点号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备状态点号">
                  <el-input
                    v-model="form.data.equipStatusKey"
                    placeholder="设备状态点号"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </TitleGroup>
        </el-form>
      </el-drawer>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import {
  Delete,
  Document,
  Download,
  Edit,
  Grid,
  Plus,
  RefreshLeft,
  Search
} from "@element-plus/icons-vue";
import { ElForm, ElMessageBox, ElNotification, ElTable } from "element-plus";
import { nextTick, onMounted, reactive, ref } from "vue";
import { getDictData } from "@/api/system";
import { downloadFile } from "@/utils";
import { useRouter } from "vue-router";
import { cloneDeep } from "@pureadmin/utils";
import {
  addVppEquipmentList,
  delVppEquipmentList,
  editVppEquipmentList,
  exportVppEquipmentList,
  getVppEquipmentList
} from "@/api/vppEquipment";
import TitleGroup from "@/components/FormRowTitle/index.vue";
const props = defineProps({
  activeVppUserId: {
    type: String
  },
  handleStatus: {
    type: String,
    default: "add"
  }
});
const router = useRouter();
const queryShow = ref(true);
const activeTerminalId = ref("");
const queryForm = reactive({
  data: {
    blurry: undefined
  }
});
const resetQuery = () => {
  queryForm.data = {
    blurry: undefined
  };
};
const search = async () => {
  pageObj.data.currentPage = 1;
  let { content, totalElements } = await getData();
  pageObj.data.total = totalElements;
  tableData.data = content;
};
const getList = async () => {
  let { content, totalElements } = await getData();
  pageObj.data.total = totalElements;
  tableData.data = content;
};
const exportData = async () => {
  let res = await exportVppEquipmentList({
    current: pageObj.data.currentPage - 1,
    size: pageObj.data.pageSize,
    sort: "id,desc",
    name: queryForm.data.blurry ? queryForm.data.blurry : undefined,
    vppTerminalId: activeTerminalId.value
  });
  downloadFile(res, "终端数据", "xlsx");
};
const handleSizeChange = () => {
  search();
};
const handleCurrentChange = async () => {
  getList();
};
const getData = () => {
  loading.value = true;
  return new Promise<any>(async (resolve, reject) => {
    let data = await getVppEquipmentList({
      current: pageObj.data.currentPage,
      size: pageObj.data.pageSize,
      sort: "id,desc",
      name: queryForm.data.blurry ? queryForm.data.blurry : undefined,
      vppTerminalId: activeTerminalId.value
    });
    loading.value = false;
    resolve(data);
  });
};
const dictList = reactive({
  data: {
    status: [],
    equipType: [],
    equipStatus: []
  }
});
const initGetData = async () => {
  const vppTerminalAssetsStatus = await getDictData({
    dictName: "vpp_terminal_assets_status"
  });
  const vppEquipType = await getDictData({
    dictName: "vpp_equip_type"
  });
  const equipStatusData = await getDictData({
    dictName: "report_device_status"
  });
  dictList.data.status = vppTerminalAssetsStatus.content.map(item => ({
    ...item,
    value: parseInt(item.value)
  }));
  dictList.data.equipType = vppEquipType.content.map(item => ({
    ...item,
    value: parseInt(item.value)
  }));
  dictList.data.equipStatus = equipStatusData.content.map(item => ({
    ...item,
    value: parseInt(item.value)
  }));
};
const dictFormat = (key, value, data) => {
  if (value) {
    let item = data.find(i => parseInt(i.value) === parseInt(value));
    if (item) {
      return item.label;
    } else {
      return "";
    }
  } else {
    return "";
  }
};
initGetData();
const tableData = reactive({
  data: []
});
const colums = reactive({
  data: [
    {
      label: "设备名称",
      prop: "name",
      width: "100px"
    },
    // {
    //   label: "负荷控制终端ID",
    //   prop: "vppTerminalId",
    //   width: "160px"
    // },
    {
      label: "设备序号",
      prop: "equipSeqNo",
      width: "120px"
    },
    {
      label: "设备类型",
      prop: "equipType",
      width: "110px"
    },
    {
      label: "设备厂家",
      prop: "equipMaker",
      width: "110px"
    },
    {
      label: "设备描述",
      prop: "equipDescr",
      width: "140px"
    },
    {
      label: "资源状态",
      prop: "status",
      width: "110px"
    },
    {
      label: "上报设备状态",
      prop: "equipStatus",
      width: "140px"
    },
    {
      label: "首次上线时间",
      prop: "initOnlineTime",
      width: "120px"
    },
    {
      label: "上线时间",
      prop: "onlineTime",
      width: "120px"
    },
    {
      label: "下线时间",
      prop: "offlineTime",
      width: "120px"
    },
    {
      label: "有功遥测点号",
      prop: "pKey",
      width: "130px"
    },
    {
      label: "无功遥测点号",
      prop: "qKey",
      width: "130px"
    },
    {
      label: "设备状态点号",
      prop: "equipStatusKey",
      width: "130px"
    },
    {
      label: "联系人",
      prop: "contactName",
      width: "120px"
    },
    {
      label: "联系电话",
      prop: "contactTel",
      width: "120px"
    }
    // {
    //   label: "创建人",
    //   prop: "createBy",
    //   width: "100px"
    // },
    // {
    //   label: "创建时间",
    //   prop: "createTime",
    //   width: "120px"
    // },
    // {
    //   label: "更新人",
    //   prop: "updateBy",
    //   width: "160px"
    // },
    // {
    //   label: "更新时间",
    //   prop: "updateTime",
    //   width: "140px"
    // }
  ]
});
const defaultColums = reactive({
  data: [
    {
      label: "设备名称",
      prop: "name",
      width: "100px"
    },
    // {
    //   label: "负荷控制终端ID",
    //   prop: "vppTerminalId",
    //   width: "160px"
    // },
    {
      label: "设备序号",
      prop: "equipSeqNo",
      width: "120px"
    },
    {
      label: "设备类型",
      prop: "equipType",
      width: "110px"
    },
    {
      label: "设备厂家",
      prop: "equipMaker",
      width: "110px"
    },
    {
      label: "设备描述",
      prop: "equipDescr",
      width: "140px"
    },
    {
      label: "资源状态",
      prop: "status",
      width: "110px"
    },
    {
      label: "上报设备状态",
      prop: "equipStatus",
      width: "140px"
    },
    {
      label: "首次上线时间",
      prop: "initOnlineTime",
      width: "120px"
    },
    {
      label: "上线时间",
      prop: "onlineTime",
      width: "120px"
    },
    {
      label: "下线时间",
      prop: "offlineTime",
      width: "120px"
    },
    {
      label: "有功遥测点号",
      prop: "pKey",
      width: "130px"
    },
    {
      label: "无功遥测点号",
      prop: "qKey",
      width: "130px"
    },
    {
      label: "设备状态点号",
      prop: "equipStatusKey",
      width: "130px"
    },
    {
      label: "联系人",
      prop: "contactName",
      width: "120px"
    },
    {
      label: "联系电话",
      prop: "contactTel",
      width: "120px"
    }
    // {
    //   label: "创建人",
    //   prop: "createBy",
    //   width: "100px"
    // },
    // {
    //   label: "创建时间",
    //   prop: "createTime",
    //   width: "120px"
    // },
    // {
    //   label: "更新人",
    //   prop: "updateBy",
    //   width: "160px"
    // },
    // {
    //   label: "更新时间",
    //   prop: "updateTime",
    //   width: "140px"
    // }
  ]
});
const loading = ref(false);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref([]);
const checkAll = ref(true);
const isIndeterminate = ref(false);
const checkedCities = ref([]);

const handleCheckAllChange = (val: boolean) => {
  checkedCities.value = val ? defaultColums.data.map(item => item.prop) : [];
  isIndeterminate.value = false;
  if (checkedCities.value.length) {
    colums.data = defaultColums.data;
  } else {
    colums.data = [];
  }
};
const pageObj = reactive({
  data: {
    currentPage: 1,
    pageSize: 10,
    total: 0
  }
});
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === defaultColums.data.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < defaultColums.data.length;
  let cols = [];
  defaultColums.data.forEach(i => {
    if (value.indexOf(i.prop) > -1) {
      cols.push(i);
    }
  });
  colums.data = cols;
};
const lookRow = row => {
  addDialog.value = true;
  status.value = "look";
  title.value = "查看设备";
  let data = cloneDeep(row);
  form.data = data;
};
onMounted(() => {
  checkedCities.value = colums.data.map(item => item.prop);
});

const form = reactive({
  data: {
    id: null,
    name: null,
    vppTerminalId: null,
    equipSeqNo: null,
    equipType: null,
    equipMaker: null,
    equipDescr: null,
    status: null,
    equipStatus: null,
    initOnlineTime: null,
    onlineTime: null,
    offlineTime: null,
    pKey: null,
    qKey: null,
    equipStatusKey: null,
    contactName: null,
    contactTel: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  },
  rules: {
    name: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
    vppTerminalId: [
      { required: true, message: "负荷控制终端ID不能为空", trigger: "blur" }
    ],
    createBy: [{ required: true, message: "创建人不能为空", trigger: "blur" }],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ]
  }
});
const ruleForm = ref<InstanceType<typeof ElForm>>();
const addDialog = ref(false);
const status = ref("add");
const title = ref("新增设备");
const addMenu = () => {
  addDialog.value = true;
  status.value = "add";
  title.value = "新增设备";
};
const handleSelectionChange = val => {
  multipleSelection.value = val;
};
const editRow = async row => {
  addDialog.value = true;
  status.value = "edit";
  title.value = "修改设备";
  let data = cloneDeep(row);
  form.data = data;
};

const delSelect = () => {
  if (multipleSelection.value.length) {
    ElMessageBox.confirm(
      `确认删除选中的${multipleSelection.value.length}条数据?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    ).then(async () => {
      await delVppEquipmentList(multipleSelection.value.map(i => i.id));
      ElNotification({
        title: "系统提示",
        message: "删除成功",
        type: "success"
      });
      search();
    });
  }
};
const editSelect = () => {
  if (multipleSelection.value.length === 1) {
    editRow(multipleSelection.value[0]);
  }
};
const delConfirm = async row => {
  await delVppEquipmentList([row.id]);
  ElNotification({
    title: "系统提示",
    message: "删除成功",
    type: "success"
  });
  search();
};
const cancel = () => {
  form.data = {
    id: null,
    name: null,
    vppTerminalId: null,
    equipSeqNo: null,
    equipType: null,
    equipMaker: null,
    equipDescr: null,
    status: null,
    equipStatus: null,
    initOnlineTime: null,
    onlineTime: null,
    offlineTime: null,
    pKey: null,
    qKey: null,
    equipStatusKey: null,
    contactName: null,
    contactTel: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  ruleForm.value.resetFields();
  nextTick(() => {
    addDialog.value = false;
  });
};
const beforeClose = d => {
  form.data = {
    id: null,
    name: null,
    vppTerminalId: null,
    equipSeqNo: null,
    equipType: null,
    equipMaker: null,
    equipDescr: null,
    status: null,
    equipStatus: null,
    initOnlineTime: null,
    onlineTime: null,
    offlineTime: null,
    pKey: null,
    qKey: null,
    equipStatusKey: null,
    contactName: null,
    contactTel: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  nextTick(() => {
    d();
  });
};
const resetForm = () => {
  form.data = {
    id: null,
    name: null,
    vppTerminalId: null,
    equipSeqNo: null,
    equipType: null,
    equipMaker: null,
    equipDescr: null,
    status: null,
    equipStatus: null,
    initOnlineTime: null,
    onlineTime: null,
    offlineTime: null,
    pKey: null,
    qKey: null,
    equipStatusKey: null,
    contactName: null,
    contactTel: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
};
const submit = () => {
  ruleForm.value.validate(async valid => {
    if (valid) {
      let data = cloneDeep(form.data);
      data.vppTerminalId = activeTerminalId.value;
      if (status.value === "add") {
        await addVppEquipmentList(data);
        ElNotification({
          title: "系统提示",
          message: "设备创建成功",
          type: "success"
        });
      } else {
        await editVppEquipmentList(data);
        ElNotification({
          title: "系统提示",
          message: "设备编辑成功",
          type: "success"
        });
      }
      resetForm();
      nextTick(() => {
        addDialog.value = false;
        search();
      });
    }
  });
};
const drawerShow = ref(false);
const init = id => {
  activeTerminalId.value = id;
  drawerShow.value = true;
  resetQuery();
  search();
};
defineExpose({
  init
});
</script>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

:deep(.el-button:focus-visible) {
  outline: none;
}

//.main-content {
//  margin: 24px 24px 0 !important;
//}

.search-form {
  :deep(.el-form-item) {
    margin-right: 4px;
    margin-bottom: 0;
  }
}

:deep(.el-drawer__header) {
  margin-bottom: 10px;
}
</style>
